package cn.itcast.myapplication.lifecycle;

import android.content.Context;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.widget.Chronometer;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;


   /**
    *
    *
    * LifeCycles(让组件感知生命周期，Activity进一步解耦)
    *
    *
    * */


public class MyChronometer extends Chronometer implements LifecycleObserver {

    private static long elapsedTime;//定义为static，它的数据就变成静态的，切屏时屏幕数据不会继续加载

    public MyChronometer(Context context, AttributeSet attrs) {

        super(context, attrs);

    }


    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)

    private void pauseMeter(){

        elapsedTime= SystemClock.elapsedRealtime()-getBase();//开始的时间减去结束的时间

        stop();//当切换屏幕时暂停计时器

    }


    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)

    private void resumeMeter(){

        setBase(SystemClock.elapsedRealtime()-elapsedTime);//开始时间减去经过的时间

        start();//当返回计时页面时继续开始计时

    }


}

